package com.soilflow.web.controller.common;

import com.soilflow.common.core.domain.AjaxResult;
import com.soilflow.common.utils.SecurityUtils;
import com.soilflow.web.domain.QiNiu;
import com.soilflow.web.utils.QiniuUtils;
import com.qiniu.util.Auth;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.util.UUID;

/**
 * 七牛云
 *
 * @author zhiwei
 * @date 2022-06-01 - 22:51
 */
@RestController
@RequestMapping("/qiniu")
public class QiNiuController {
    @GetMapping("/getToken")
    public QiNiu getTokenInfo() throws ParseException {
        QiNiu qiNiu = new QiNiu();
        String accessKey = "4JbdAqrR-EVuPaRsOWxp8XlhOga0eeKFenJ6Q4Dd";
        String secretKey = "Xk_pPQtS4QF63pnAVbiFpYnStsTMEcB97D38VKmh";
        String bucket = "caigentuan";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        qiNiu.setToken(upToken);
        return qiNiu ;
    }

    //图片上传
    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult upload(@RequestPart("imgFile") MultipartFile imgFile){
        try{
            //获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf - 1);
            //使用UUID随机产生文件名称，防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //图片上传成功
            //AjaxResult result = new AjaxResult();
            return AjaxResult.success(fileName);
        }catch (Exception e){
            e.printStackTrace();
            //图片上传失败
            return AjaxResult.error("上传失败");
        }
    }
}

